#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-5 下午4:50
import StringIO
import mimetypes

from flask import Flask, Response
from werkzeug.datastructures import Headers
import xlwt

app = Flask(__name__)


@app.route("/export/")
def export_view():
    """
    显示了动态生成excel文件，返回给response流

    :return:
    """
    response = Response()
    response.status_code = 200

    workbook = xlwt.Workbook(encoding='utf-8')
    sheet = workbook.add_sheet("sheet1", cell_overwrite_ok=True)
    sheet.write(1, 1, u'测试')

    # 关键是下面这两行
    output = StringIO.StringIO()
    workbook.save(output)

    response.data = output.getvalue()

    file_name = 'data.xls'
    mimetype_tuple = mimetypes.guess_type(file_name)

    response_headers = Headers({
        'Pragma': "public",  # required,
        'Expires': '0',
        'Cache-Control': 'must-revalidate, post-check=0, pre-check=0,private',
        # 'Cache-Control': 'private',  # required for certain browsers,
        'Content-Type': mimetype_tuple[0],
        'Content-Disposition': 'attachment; filename=\"%s\";' % file_name,
        'Content-Transfer-Encoding': 'binary',
        'Content-Length': len(response.data)
    })

    if not mimetype_tuple[1] is None:
        response_headers.update({
            'Content-Encoding': mimetype_tuple[1]
        })

    response.headers = response_headers
    response.set_cookie('fileDownload', 'true', path='/')

    return response


@app.route("/binary/")
def export_binary_file():
    """
    显示了读取一个二进制的文件，然后重定向到response流

    :return:
    """
    response = Response()
    response.status_code = 200

    f = open("app.py", 'rb')

    file_name = 'app.py'
    response.data = f.read()
    f.close()
    mimetype_tuple = mimetypes.guess_type(file_name)

    response_headers = Headers({
        'Pragma': "public",  # required,
        'Expires': '0',
        'Cache-Control': 'must-revalidate, post-check=0, pre-check=0,private',
        # 'Cache-Control': 'private',  # required for certain browsers,
        'Content-Type': mimetype_tuple[0],
        'Content-Disposition': 'attachment; filename=\"%s\";' % file_name,
        'Content-Transfer-Encoding': 'binary',
        'Content-Length': len(response.data)
    })

    if not mimetype_tuple[1] is None:
        response_headers.update({
            'Content-Encoding': mimetype_tuple[1]
        })

    response.headers = response_headers
    response.set_cookie('fileDownload', 'true', path='/')

    return response


if __name__ == '__main__':
    app.debug = True
    app.run(host="0.0.0.0", port=8080)